package com.mugui.spring.net.baghandle;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

public class NetBagInterceptor implements HandlerInterceptor {

	private static HashMap<String, AtomicInteger> map = new HashMap<>();
	private static long map_time = 0;

	private static String https[]= {"39.105.201.42","47.52.219.55"};
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (System.currentTimeMillis() - map_time > 60000) {
			map.clear();
			map_time = System.currentTimeMillis();
		}
		String remoteHost = request.getRemoteHost();
		for (String str : https) {
			if (remoteHost.equals(str))
				return true;
		}
		AtomicInteger integer = map.get(remoteHost);
		if (integer == null) {
			synchronized (NetHandle.class) {
				integer = map.get(request.getRemoteHost());
				if (integer == null) {
					integer = new AtomicInteger(0);
					map.put(request.getRemoteHost(), integer);
				}
			}
		}
		integer.getAndIncrement();
		if (integer.intValue() > 1000) {
			System.out.println(integer + "恶意请求者：" + request.getRemoteHost() + " :" + request.getRemotePort());
			return false;
		}

		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

}
